package com.peng.leetcode.sort;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Intersection
 *
 * @author: lupeng6
 * @create: 2020/12/10 16:16
 */
public class Intersection {

    public static void main(String[] args) {
        int[] nums1 = {4, 9, 5};
        int[] nums2 = {9, 4, 9, 8, 4};
        int[] intersection = new Solution().intersection(nums1, nums2);
        for (int i : intersection) {
            System.out.println(i);
        }
    }

    static class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            int l1 = nums1.length;
            int l2 = nums2.length;
            if (l1 == 0 || l2 == 0) {
                return new int[0];
            }
            List<Integer> ret = new ArrayList<>();
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i < l1; i++) {
                set.add(nums1[i]);
            }
            for (int i = 0; i < l2; i++) {
                if (set.contains(nums2[i])) {
                    ret.add(nums2[i]);
                    set.remove(nums2[i]);
                }
                if (set.isEmpty()) {
                    break;
                }
            }
            return ret.stream().mapToInt(Integer::valueOf).toArray();
        }
    }
}
